package cn.jiyun.controller;

import cn.jiyun.constant.MessageConstant;
import cn.jiyun.constant.RedisMessageConstant;
import cn.jiyun.entity.Result;
import cn.jiyun.pojo.Member;
import cn.jiyun.serivce.LoginService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private LoginService loginService;

    @RequestMapping("check")
    public Result check(@RequestBody Map<String,Object> map, HttpServletResponse response){
        try {

            String telephone = (String)map.get("telephone");
            String validateCode = (String)map.get("validateCode");
            Jedis jedis = jedisPool.getResource();
            String code = jedis.get(RedisMessageConstant.SENDTYPE_LOGIN + ":" + telephone);
//            1、校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
            if(!code.equals(validateCode)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
//            2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
            Member member = loginService.isMember(telephone);
//            3、向客户端写入Cookie，内容为用户手机号
            Cookie cookie = new Cookie("login_tel",telephone);
            cookie.setPath("/");
            response.addCookie(cookie);
//            4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
            jedis.setex(telephone,60*30, JSONObject.toJSONString(member));

            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }
    }
}
